var BrackedTagsAlgorithm = Class.create(Algorithm, {
	loadCache : function() {
		var self = this;
		self.algorithm.clearRoot.apply(self, [function() {
					var cache = bookmarkStorage.getCache();
					for (var md5 in cache) {
						var bookmark = cache[md5];
						if (bookmark.name && bookmark.url) {
							window.setTimeout(function() {
										chrome.bookmarks.create({
													parentId : self.rootId,
													title : bookmark.name
															+ BrackedTagsAlgorithm
																	.getTags(bookmark),
													url : bookmark.url
												});
									}, 100);

						}
					}
				}]);
	},
	load : function() {
		var self = this;
		var w = window;
		if (!this.rootId) {
			self.loadJob.done();
			return;
		}
		try {
			chrome.bookmarks.getChildren(this.rootId, function(results) {
				results.each(function(result) {
							bookmarkStorage.updateBookmark({
										urlMD5 : MD5(result.url),
										url : result.url,
										name : result.title,
										time : new Date(result.dateGroupModified)
									}, 'local');
						});
				w.setTimeout(function() {
							self.loadJob.done();
							self.loadCallback({
										jobId : id
									});
						}, 10);
			});
		} catch (e) {
			console.dir(e.stack || e);
		}
	},
	internalAddBookmark : function(bookmark) {
		chrome.bookmarks.create({
					parentId : this.rootId,
					title : bookmark.name
							+ BrackedTagsAlgorithm.getTags(bookmark),
					url : bookmark.url
				});
	},

	internalChangeTag : function(bookmark, newTags) {
		chrome.bookmarks.getChildren(this.rootId, function(results) {
					results.each(function(result) {
								if (result.url == bookmark.url
										|| MD5(result.url) == bookmark.urlMD5) {
									chrome.bookmarks.update(result.id, {
												title : bookmark.name
														+ BrackedTagsAlgorithm
																.getTags(bookmark)
											})
								}
							});
				});
	}
});

BrackedTagsAlgorithm.getTags = function(bookmark) {
	if (!bookmark.tags || !bookmark.tags.length)
		return '';
	var tags = [];
	bookmark.tags.each(function(tag) {
				tags.push('<' + tag + '>');
			});
	return ' ' + tags.join(' ');
};
BrackedTagsAlgorithm.getBookmark = function(treeNode) {
	if (treeNode.url) {
		var resultTages = treeNode.title.match(/(\s*?\<(.*?)\>)*$/);
		var tags = [];
		resultTages.each(function(part) {
					if (part && part.length > 2)
						tags.push(part.substr(1, part.length - 2));
				});
		return {
			urlMD5 : MD5(treeNode.url),
			url : treeNode.url,
			tags : tags,
			time : new Date(treeNode.dateGroupModified)
		};
	}
}